var ModuleUtil = {
  resolutionRatio: null,

  getTableConfig: function (data) {
    if (data === null) {
      var tableConfig = this.getShowCol();
      return Promise.resolve(tableConfig);
    }

    var apiName = '';
    var postData = {
      type: 1,
      linkId: data.serialNo
    };
    var applyId = data.applyId;
    if (SysUtil.isEmpty(applyId)) {
      apiName = 'createOrderForBomOrder/getSystemTableConfigForBomOrder';
    } else {
      apiName = 'createOrderForBomOrder/getSystemTableConfigForBomOrderForApply';
      postData.applyId = applyId;
    }

    var self = this;
    return ajaxRequest(apiName, postData).then(function (res) {
      var hideColumn = undefined;
      if (res !== null) {
        hideColumn = res.hideColumn;
        hideColumn = JSON.parse(hideColumn);
      }
      var tableConfig = self.getShowCol(hideColumn);
      return tableConfig;
    });
  },

  getShowCol: function (hideColumn) {
    if (hideColumn === undefined) {
      hideColumn = {};
    }

    var tableConfig = {};
    var tableCol = BomMaterialFormModel.tableCol;
    var classifyLevel = BomMaterialFormModel.classifyLevel;
    var fields = ['materialColorBomCol', 'materialBomCol', 'subsidiaryBomCol'];
    for (var i = 0; i < fields.length; i++) {
      var field = fields[i];
      var tableColConfig = tableCol[field];
      var hideColName = hideColumn[field];
      if (hideColName === undefined) {
        hideColName = _.cloneDeep(classifyLevel);
      }
      tableColConfig = _.filter(tableColConfig, function (obj) {
        return hideColName.indexOf(obj.id) !== -1;
      });

      var hideFields = _.map(tableColConfig, 'id');
      for (var j = 0; j < classifyLevel.length; j++) {
        var classifyField = classifyLevel[j];
        if (hideColName.indexOf(classifyField) !== -1) {
          hideFields.push(classifyField);
        }
      }
      tableConfig[field] = hideFields;
    }
    return tableConfig;
  },

  getBeforeUpdateBom: function (bomMaterial, bomForm) {
    return Promise.all([
      this.getBeforeUpdateData(bomMaterial),
      this.setEnclosurePicUrl(bomForm)
    ]).then(function (res) {
      return res[0];
    });
  },

  getBeforeUpdateData: function (bomMaterial) {
    return ajaxRequest('createOrderForBomOrder/getBomOrderById', {
      id: bomMaterial.id
    }).then(function (data) {
      var beforeBomForm = new BomMaterialFormModel(undefined, data);
      return beforeBomForm;
    });
  },

  setEnclosurePicUrl: function (bomForm) {
    return ajaxRequest('fileManager/getFileList', {
      orderNo: bomForm.serialNo,
      type: 11,
      fileName: 'enclosurePicUrl'
    }).then(function (data) {
      var enclosurePicUrl = _.map(data, 'url');
      enclosurePicUrl = _.uniq(enclosurePicUrl);
      bomForm.setEnclosurePicUrl(enclosurePicUrl);
      return bomForm;
    });
  },

  getSize: function (value) {
    value = value.trim();
    if (value === '') {
      return null;
    }
    var index1 = value.indexOf('*');
    var index2 = value.indexOf('-');
    if ((index1 === -1 && index2 === -1) || (index1 > -1 && index2 > -1)) {
      return null;
    }

    var size;
    if (index1 > -1) {
      size = value.split('*');
    } else {
      size = value.split('-');
    }
    if (size.length > 3 || size.length < 2) {
      return null;
    }

    for (var i = 0; i < size.length; i++) {
      var s = size[i];
      if (s === '') {
        return null;
      }
      s = Number(s);
      if (_.isNaN(s)) {
        return null;
      }
      size[i] = s;
    }

    return size;
  },

  calCutMaterial: function (obj, option) {
    var materialType = obj.materialType;
    if (materialType === '') {
      return null;
    }

    materialType = materialType.materialType;
    var type = option.type;
    if (type === 'ringSize') {
      if (materialType !== '板材圈') {
        return null;
      }
    } else if (type === 'legSize') {
      if (materialType !== '板材肶') {
        return null;
      }
    } else {
      return null;
    }

    var size = option.size;
    var materialObj = obj.materialObj;
    if (materialObj === null) {
      return null;
    }

    var materialModel = materialObj.materialModel;
    materialModel = this.getSize(materialModel);
    if (materialModel === null) {
      return null;
    }

    var materialKlfs = obj.materialKlfs;
    if (materialKlfs === '') {
      return null;
    }

    var klLongth = size[0];
    var klWidth = size[1];
    var modelLongth = materialModel[0];
    var modelWidth = materialModel[1];
    var projectConfig = option.projectConfig;
    var lengthSide = projectConfig.lengthDb;
    lengthSide = lengthSide === undefined ? 0 : lengthSide;
    var widthSide = projectConfig.widthDb;
    widthSide = widthSide === undefined ? 0 : widthSide;
    var lengthCut = projectConfig.lengthCut;
    lengthCut = lengthCut === undefined ? 0 : lengthCut;
    var widthCut = projectConfig.widthCut;
    widthCut = widthCut === undefined ? 0 : widthCut;

    modelLongth -= lengthSide;
    modelWidth -= widthSide;
    klLongth -= lengthCut;
    klWidth -= widthCut;

    var data = {
      klLongth: klLongth,
      klWidth: klWidth,
      modelLongth: modelLongth,
      modelWidth: modelWidth
    };

    var count = null;
    switch (materialKlfs) {
      case '横开':
        count = this.calCutMaterialByX(data);
        break;
      case '竖开':
        count = this.calCutMaterialByY(data);
        break;
      case '双向':
        count = this.calCutMaterialByXY(data);
        break;
    }

    if (count === null) {
      count = undefined;
    }

    return count;
  },

  calMaterialCutData: function (bomForm, materialData) {
    var materialType = materialData.materialType;
    if (materialType === '') {
      return null;
    }
    materialType = materialType.materialType;
    var type;
    if (materialType === '板材圈') {
      type = 'ringSize';
    } else if (materialType === '板材肶') {
      type = 'legSize';
    } else {
      return null;
    }
    var size = bomForm[type];
    size = this.getSize(size);
    if (size === null) {
      return null;
    }

    return this.calCutMaterial(materialData, {
      size: size,
      type: type,
      projectConfig: bomForm.projectConfig
    });
  },

  calCutMaterialByX: function (data) {
    var modelLongth = data.modelLongth,
      modelWidth = data.modelWidth,
      klLongth = data.klLongth,
      klWidth = data.klWidth;

    var count = Math.floor(modelWidth / klLongth) * Math.floor(modelLongth / klWidth);
    if (isNaN(count) || Math.abs(count) === Infinity) {
      return null;
    }
    return _.floor(count, 0);
  },

  calCutMaterialByY: function (data) {
    var modelLongth = data.modelLongth,
      modelWidth = data.modelWidth,
      klLongth = data.klLongth,
      klWidth = data.klWidth;

    var count = Math.floor(modelWidth / klWidth) * Math.floor(modelLongth / klLongth);
    if (isNaN(count) || Math.abs(count) === Infinity) {
      return null;
    }
    return _.floor(count, 0);
  },

  calCutMaterialByXY: function (data) {
    var xCount = this.calCutMaterialByX(data);
    var yCount = this.calCutMaterialByY(data);

    if (xCount === null || yCount === null) {
      return null;
    }

    var modelLongth = data.modelLongth,
      modelWidth = data.modelWidth,
      klLongth = data.klLongth,
      klWidth = data.klWidth;
    var yRate = modelLongth - Math.floor(modelLongth / klLongth) * klLongth;
    var yRateTotal = Math.floor(yRate / klWidth) * Math.floor(modelWidth / klLongth);
    if (isNaN(yRateTotal) || Math.abs(yRateTotal) === Infinity) {
      return xCount;
    }

    yCount += yRateTotal;
    if (xCount >= yCount) {
      return xCount;
    }
    return yCount;
  },

  getWasteRateList: function (type, bomMaterial) {
    if (type === 'add') {
      return ajaxRequest('createOrderForBomOrder/getWasteRateList', {
        status: 1
      }).then(function (res) {
        var wasteRateList = res.returnData;
        return wasteRateList;
      });
    }

    var applyId = bomMaterial.applyId;
    var postData = {
      serialNo: bomMaterial.serialNo
    };
    if (!SysUtil.isEmpty(applyId)) {
      postData.applyId = applyId;
    }
    return ajaxRequest('createOrderForBomOrder/getWasteRateForBomSelf', postData).then(function (wasteRateList) {
      return wasteRateList;
    });
  },

  toSaveTableColConfig: function (data, tableConfig, user) {
    var apiName;
    var postData = {
      tableName: 'bom-material-setting',
      hideColumn: JSON.stringify(tableConfig),
      type: 1,
      linkId: data.serialNo
    };
    var applyId = data.applyId;
    if (!SysUtil.isEmpty(applyId)) {
      apiName = 'createOrderForBomOrder/updateSystemTableConfigForBomOrderForApply';
      postData.applyId = applyId;
    } else {
      apiName = 'createOrderForBomOrder/updateSystemTableConfigForBomOrder';
    }
    return ajaxRequest(apiName, postData).then(function () {
      var configData = localStorage.getItem('bomMaterialConfigData');
      if (configData === null) {
        configData = {};
      }
      var bomMaterialConfigData = {
        serialNo: data.serialNo,
      };
      if (!SysUtil.isEmpty(applyId)) {
        bomMaterialConfigData.applyId = applyId;
      }
      configData[user.companyId] = bomMaterialConfigData;
      localStorage.setItem('bomMaterialConfigData', JSON.stringify(configData));
      return true;
    });
  },

  toSaveOtherImgs: function (data, imgs) {
    var url = imgs.join(',');
    return ajaxRequest('fileManager/uploadFileForPrint', {
      order_no: data.serialNo,
      type: 11,
      file_name: 'enclosurePicUrl',
      url: url
    }).then(function () {
      return url;
    });
  },

  toSaveWasterRateConfig: function (data, wasteRateList) {
    var applyId = data.applyId;
    var serialNo = data.serialNo;
    wasteRateList = _.map(wasteRateList, function (wasteObj) {
      var wasteRate = wasteObj.wasteRate;
      wasteRate = _.round(wasteRate / 100, 3);

      var obj = {
        orderTotalStart: wasteObj.orderTotalStart,
        orderTotalEnd: wasteObj.orderTotalEnd,
        wasteRate: wasteRate,
        wasteTotal: wasteObj.wasteTotal,
        status: 1,
        serialNo: serialNo
      };
      if (!SysUtil.isEmpty(applyId)) {
        obj.applyId = applyId;
      }
      return obj;
    });

    return ajaxRequest('createOrderForBomOrder/saveWasteRateForBomSelf', {
      dataStr: JSON.stringify(wasteRateList)
    }).then(function () {
      return true;
    });
  },

  getPixelValue: function (value, type) {
    var resolutionRatio = this.getResolutionRatio();
    var value = value / 25.4 * resolutionRatio;
    value = _.round(value, 4);
    if (type === 'round') {
      value = _.round(value, 0);
    } else if (type === 'floor') {
      value = Math.floor(value);
    } else if (type === 'ceil') {
      value = Math.ceil(value);
    }
    return value;
  },

  getResolutionRatio: function () {
    var resolutionRatio = this.resolutionRatio;
    if (resolutionRatio !== null) {
      return resolutionRatio;
    }

    var value = SysUtil.formatUnit2px(1, 'in');
    if (SysUtil.isEmpty(value) || value === 0) {
      value = SysUtil.formatUnit2px(100, 'mm', false);
      value = _.round(value * 25.4 / 100, 0);
    }
    this.resolutionRatio = value;
    return value;
  },

  checkValid: function (materialCutData) {
    var fields = ['khhc', 'khhk', 'ztkd', 'ztcd', 'cutGap'];
    for (var i = 0; i < fields.length; i++) {
      var field = fields[i];
      var value = materialCutData[field];
      if (value === undefined) {
        return field;
      }
    }

    var ztcd = materialCutData.ztcd;
    var khhc = materialCutData.khhc;
    var totalcd = _.round(ztcd * 2, 3);
    if (totalcd > khhc) {
      return 'totalcd>khhc';
    }

    var ztkd = materialCutData.ztkd;
    var khhk = materialCutData.khhk;
    var totalkd = _.round(ztkd * 2, 3);
    if (totalkd > khhk) {
      return 'totalkd>khhk';
    }

    return '';
  },

  calRingMaterialListCut: function (postData) {
    return ajaxRequest('kaiLiao/kaiLiaos', {
      dataStr: JSON.stringify(postData)
    }, false).then(function (dataList) {
      if (!_.isArray(dataList)) {
        var info = dataList.info;
        throw info;
      }

      dataList = _.map(dataList, function (data, index) {
        var kllx = postData[index].kllx700;
        var obj = {};
        if (kllx === 1) {
          obj = {
            horizontalCol: data.result1,
            horizontalRow: data.result2,
            verticalCol: 0,
            verticalRow: 0,
            type: 1
          };
        } else if (kllx === 2) {
          obj = {
            horizontalCol: 0,
            horizontalRow: 0,
            verticalCol: data.result1,
            verticalRow: data.result2,
            type: 2
          };
        } else if (kllx == 3) {
          var type = data.result5;
          if (type === 1) {
            obj = {
              horizontalCol: data.result1,
              horizontalRow: data.result2,
              verticalCol: data.result3,
              verticalRow: data.result4,
              type: type
            };
          } else {
            obj = {
              horizontalCol: data.result3,
              horizontalRow: data.result4,
              verticalCol: data.result1,
              verticalRow: data.result2,
              type: type
            };
          }
        }

        return obj;
      });

      return dataList;
    });
  }
};

var BomMaterialFormUtil = {
  calMaterialListCut: function (bomForm, materialDataList) {
    var materialCutData = bomForm.materialCutData;
    if (materialCutData.khhc === undefined) {
      return Promise.resolve([]);
    }

    if (_.isArray(materialDataList)) {
      materialDataList = _.filter(materialDataList, function (material) {
        var materialType = _.get(material, 'materialType.materialType', '');
        return materialType === '板材圈';
      });
    } else {
      materialDataList = [materialDataList];
    }
    if (materialDataList.length === 0) {
      return Promise.resolve([]);
    }

    var materialPostData = {
      khhc58: materialCutData.khhc,
      khhk59: materialCutData.khhk,
      ztcd61: materialCutData.ztcd,
      ztkd60: materialCutData.ztkd,
      qf717: materialCutData.cutGap,
      xbl55: 0
    };

    var materials = [];
    var postDataList = [];
    var materialKlfsObj = {
      "横开": 1,
      "竖开": 2,
      "双向": 3
    };
    for (var i = 0; i < materialDataList.length; i++) {
      var material = materialDataList[i];
      var materialObj = material.materialObj;
      if (materialObj === null) {
        continue;
      }

      var materialKlfs = material.materialKlfs;
      if (materialKlfs === '') {
        continue;
      }

      var materialModel = materialObj.materialModel;
      var arr = ModuleUtil.getSize(materialModel);
      if (arr === null) {
        continue;
      }

      var beatEdge = material.beatEdge;
      if (beatEdge === undefined) {
        beatEdge = 0;
      }
      var postData = _.cloneDeep(materialPostData);
      postData.ylc52 = arr[0];
      postData.ylk53 = arr[1];
      postData.sbl54 = beatEdge;

      postData.kllx700 = materialKlfsObj[materialKlfs];
      postDataList.push(postData);
      materials.push(material);
    }

    if (materials.length === 0) {
      return Promise.resolve([]);
    }

    return ModuleUtil.calRingMaterialListCut(postDataList).then(function (dataList) {
      for (var i = 0; i < dataList.length; i++) {
        var obj = dataList[i];
        var material = materials[i];
        var materialMtlktTotal = obj.horizontalRow * obj.horizontalCol + obj.verticalRow * obj.verticalCol;
        materialMtlktTotal = _.round(materialMtlktTotal, 0);
        material.materialMtlktTotal = materialMtlktTotal;
        material.materialFeedTotalRate = _.round(1 / materialMtlktTotal, 4);
        material.materialObj.materialCut = obj;
      }
    });
  }
};

var RingSizeCompUtil = {
  calMaterialListCut: function (materialCutData, materialList) {
    var materialPostData = {
      khhc58: materialCutData.khhc,
      khhk59: materialCutData.khhk,
      ztcd61: materialCutData.ztcd,
      ztkd60: materialCutData.ztkd,
      qf717: materialCutData.cutGap,
      sbl54: 0,
      xbl55: 0
    };

    var postDataList = [];
    var kllxList = [1, 2, 3];
    for (var i = 0; i < materialList.length; i++) {
      var material = materialList[i];
      for (var j = 0; j < kllxList.length; j++) {
        var postData = _.cloneDeep(materialPostData);
        postData.kllx700 = kllxList[j];
        postData.ylc52 = material.ylc;
        postData.ylk53 = material.ylk;
        postDataList.push(postData);
      }
    }

    return ModuleUtil.calRingMaterialListCut(postDataList).then(function (dataList) {
      var dataIndex = 0;
      var fields = ['horizontalCut', 'verticalCut', 'bothCut']
      for (var i = 0; i < materialList.length; i++) {
        var material = materialList[i];
        for (var j = 0; j < fields.length; j++) {
          var field = fields[j];
          var obj = dataList[dataIndex];
          var value = obj.horizontalRow * obj.horizontalCol + obj.verticalRow * obj.verticalCol;
          value = _.round(value, 0);
          material[field] = value;
          dataIndex++;
        }
      }
      return materialList;
    });
  }
};
